<?php
/**
 * mp
 * User: wayne
 * Date: 2015-09-08
 */
namespace Wx\Model;
use Common\Api\Wx\Wechat;
use Think\Exception;
use Think\Model;
use Common\Api\Weixin;

class WxMpModel extends Model {

    /**
     * 向微信发送客服消息
     * @param $batchIdArr
     * @return bool
     */
    public function wxSms($batchIdArr){
        try{
            if(!$batchIdArr) return false;

            $emsModel = D('Home/Ems');
            $map['batch_id'] = array('IN', $batchIdArr);
            $map['phone'] = array('exp','is not null');

            $filed = 'knxf_ems.code,knxf_ems.partnerid,knxf_ucenter_member.openid';
            $lists = $emsModel->where($map)->field($filed)->select();
            //$sql = $emsModel->getLastSql();

            if($lists){
                //获取微信发送消息后缀
                $partnerid = $lists[0]['partnerid'];
                $suffix = $this->_getSuffix($partnerid);

                //获取微信
                $where['app_id'] = C('APP_ID');
                $app_info = $this->where($where)->find();
                $options = array(
                    'token' => $app_info['data_fetcher_token'], // 填写你设定的key
                    'appid' => $app_info['app_id'],
                    'appsecret' => $app_info['app_secret']
                );

                $weObj = new Wechat($options);
                $sendLogModel = D('Home/SmsSendLog');
                foreach ($lists as $ems){
                    $content = "您好，您的快件单号{$ems['code']}$suffix";
                    //发送微信
                    $reply_message = array (
                        'touser' => $ems['openid'],
                        'msgtype' => 'text',
                        'text' => array ('content' => $content)
                    );
                    $ret = $weObj->sendCustomMessage($reply_message);

                    //存储发送记录信息
                    $tmp = array();
                    if(!$ret){
                        $tmp['status'] = $sendLogModel::STATE_FAIL;
                        error_log("[wxSms err]".$weObj->errCode . '-' . $weObj->errMsg."\r\n",3,"/tmp/wyq_mp_log.log");
                    }else{
                        $tmp['status'] = $sendLogModel::STATE_SUCC;
                    }
                    $tmp['openid']  = $ems['openid'];
                    $tmp['uid']     = $partnerid;
                    $tmp['content'] = $content;
                    $tmp['msg_type'] = $sendLogModel::MSG_TYPE_WX;
                    $tmp['create_time'] = time();
                    $tmp['update_time'] = time();

                    $flag = $sendLogModel->add($tmp);
                    if(!$flag){
                        error_log("[wxSms log err]".$sendLogModel->getLastSql()."\r\n",3,"/tmp/wyq_mp_log.log");
                    }
                }
            }

            return true;
        }catch (Exception $e){
            error_log("[wxSms Exception]".$e->getCode() . '-' . $e->getMessage()."\r\n",3,"/tmp/wyq_mp_log.log");
            return false;
        }
    }

    /**
     * 获取微信发送消息后缀
     * @param $partnerid
     * @return bool|string
     */
    private function _getSuffix($partnerid){
        try{
            if(!$partnerid) return false;

            $memModel = D('Home/Member');
            $map_site['uid'] = $partnerid;
            $siteInfo = $memModel->field('phone,store_name,address,province,city,district')->where($map_site)->find();

            //获取驿站地理信息
            $division = '';
            if($siteInfo['address']){
                $division = $siteInfo['address'];
            }elseif($siteInfo['province']){
                $divModel = D('Home/Division');
                $province = $divModel->getPkByName($siteInfo['province']);

                $city = $district = '';
                if($siteInfo['city']){
                    $city = $divModel->getPkByName($siteInfo['city'], $siteInfo['province']);

                    if($siteInfo['district']){
                        $district = $divModel->getPkByName($siteInfo['district'], $siteInfo['city']);
                    }
                }

                $division = $province . $city . $district;
            }

            $site_division = $division . "  " . $siteInfo['store_name'];
            $suffix = "已投递至快鸟驿站（{$site_division}），请您在空闲时间尽快领取，快鸟驿站电话：{$siteInfo['phone']}，快鸟驿站免提货费。";

            return $suffix;
        }catch (Exception $e){
            $this->error = '数据异常';
            return false;
        }
    }

    /**
     * 获取accessToken
     * @name getAccessToken
     */
    public function getAccessToken($appId){
        $cacherId = Weixin\WeiXinApi2::WEXIN_ACCESS_TOKEN . $appId;
        $ret = S($cacherId);
        if(false == $ret){
            $ret = $this->reflushAccessToken($appId);
            S($cacherId, $ret, 6900);
        }
        return $ret;
    }

    /**
     * 刷新accessToken
     * @name reflushAccessToken
     */
    public function reflushAccessToken($appId){
        $appInfo = $this->where(array('app_id'=>$appId))->find();
        $wxClient = Weixin\WeiXinApiCore::getClient($appInfo['app_id'], $appInfo['app_secret']);
        return $wxClient->getToken();
    }

    /* 组织模型自动完成 */
    protected $_auto = array (
        array('last_update_time', 'getDateTimes', self::MODEL_BOTH, 'callback'),
        array('create_time', 'getDateTimes', self::MODEL_INSERT, 'callback'),
    );

    /* 组织模型自动验证 */
    protected $_validate = array (
        //array('organiz_id', 'require', '组织id不能为空！', self::MUST_VALIDATE, '', self::MODEL_INSERT),
        array('app_id', 'require', 'AppId不能为空！', self::MUST_VALIDATE, '', self::MODEL_INSERT),
        array('app_id','1,50','AppId不能超过20个字符！', self::EXISTS_VALIDATE , 'length'),
        array('app_secret', 'require', 'AppSecret不能为空！', self::MUST_VALIDATE, '', self::MODEL_INSERT),
        array('app_secret','1,100','AppSecret不能超过40个字符！', self::EXISTS_VALIDATE , 'length'),
        array('app_name', 'require', '微信公众号名称不能为空！', self::MUST_VALIDATE, '', self::MODEL_INSERT),
        array('app_wx_id', 'require', '微信号不能为空！', self::MUST_VALIDATE, '', self::MODEL_INSERT),
        array('uid', 'require', '运营人员id不能为空！', self::MUST_VALIDATE, '', self::MODEL_INSERT),
    );

    /**
     * 添加公众号
     */
    public function addPublic($public_data){
        /*
         * 绑定成功，或同一个用户；不可重复绑定
        $where['uid']       = $public_data['app_id'];
        $where['status']    = 3;
        $where['_logic']    = 'OR';

        $map['_complex']    = $where;
        */
        $map['app_id']      = $public_data['app_id'];
        //检测公众号名称是否可用
        $name_map['app_name'] = $public_data['app_name'];
        $name_map['status'] = 3;
        $name_info = $this->where($name_map)->find();
        if($name_info){
            $this->error = '该公众号名称已存在，请修改名称';
            return false;
        }
        $public_info = $this->where($map)->order('mp_id desc')->find();
        if (empty($public_info)) {
            return $this->add($public_data);
        } else {
            if($public_info['status'] == 3) {  //正常绑定过的不允许再次绑定
                $this->error = '该帐号已存在，请勿重复绑定';
                return false;
            }else{
                if($public_info['mp_id']){
                    //$update_map['status'] = 1; //设置为未审核状态
                    $reslut = $this->where(array('mp_id'=>$public_info['mp_id']))->save($public_data);
                    if($reslut === false){
                        $this->error = '绑定失败，请重新再试';
                    }else{
                        return $public_info['mp_id'];
                    }
                }
            }
        }
    }

    /**
     * 获得当前datetime
     */
    public function getDateTimes(){
        return date('Y-m-d H:i:s');
    }

    /**
     * 根据id获取公众号详情
     */
    public function getInfoById($mp_id){
        return $this->where(array('mp_id'=>$mp_id))->find();
    }
    /**
     * 根据appid获取公众号详情
     */
    public function getInfoByAppId($appId){
    	return $this->where(array('app_id'=>$appId))->find();
    }
    /**
     * 根据id获取公众号详情
     */
    public function getInfoOrgById($mp_id){
        return $this->field('a.*, o.name')->alias('a')->join('__ORGANIZATION__ as o on o.id = a.organiz_id', 'left')->where(array('mp_id'=>$mp_id))->find();
    }
    
    /**
     * 开发者微信号获得微信信息
     */
    public function getInfoByAppName($appname) {
        return $this->where(array('app_wx_id'=>$appname))->find();
    }

    /**
     * 获取用户拥有的公众号
     *
     * @param string $uid
     */
    public function getByUid($uid, $organiz_id = null) {
//         $sql = "select mp.*,m.nickname,m.header from {$this->tablePrefix}wx_mp as mp
//                 left join {$this->tablePrefix}member as m on mp.uid = m.uid
//                 where mp.status=4 and mp.uid={$uid}";
//         if(!is_null($organiz_id)){
//             $sql .= ' and mp.organiz_id = '.$organiz_id;
//         }else{
//             $sql .= ' and mp.organiz_id = 0';
//         }
//         return $this->query($sql);

//         $sql = "select mp.*,me"
        return $this->where(array('uid' => $uid, 'status' => 3))->select();
    }

    
    /**
     * 获得全部公众号列表
     * @param $uid
     * @param $oids
     * @return array
     */
    public function getAllMpList($uid, $oids){
        //获得公众号的活动id
        $mpIds = D('Organization/MemberPriv')->getShareMpid($oids);
        if(empty($mpIds)){
            if (!empty($oids)) {
                $where = "(a.uid = $uid or a.organiz_id in (".implode(',', $oids).")) and a.status = 3 or a.status = 1";
            } else {
                $where = "a.uid = $uid and a.status = 3 or a.status = 1 ";
            }
            
        }else{
            $where = "(a.uid = $uid or a.mp_id in (".implode(',', $mpIds).")) and a.status = 3  or a.status = 1 ";
        }
        return $this->alias('a')
        ->field(array('a.*','o.name','o.logo','m.header','m.nickname'))
        ->join(array(
            'LEFT JOIN __ORGANIZATION__ AS o ON o.id=a.organiz_id',
            'LEFT JOIN __MEMBER__ AS m ON m.uid=a.uid'
        ))
        ->where($where)
        ->order(array('a.create_time'=>'desc'))
        ->select();
    }
    
    /**
     * 获取个人公众号
     * @param $uid
     * @return array
     */
    public function getPersonMpList($uid){        
        $mp_id_list = session('user_auth.mp_list');
        if ( is_array($mp_id_list) ){
            $where = array('mp_id'=> array('in', $mp_id_list), 'status'=>array('in','1,3'));
        } else {
            $where = array('uid'=>$uid, 'status'=>array('in','1,3'));
        }
        return $this->where($where)
            ->order(array('create_time'=>'desc'))
            ->select();
    }
    
    /**
     * 获得对应组织的活动
     * @param $organiz_id
     */
    public function getOrganMpList($organiz_id){
        return $this->alias('a')
        ->field(array('a.*','o.name','o.logo','m.header','m.nickname'))
        ->join(array(
            'LEFT JOIN __ORGANIZATION__ AS o ON o.id=a.organiz_id',
            'LEFT JOIN __MEMBER__ AS m ON m.uid=a.uid'
        ))
        ->where("a.organiz_id = ".addslashes($organiz_id)." and a.status = 3")
        ->order(array('a.create_time'=>'desc'))
        ->select();
    }
    
    /**
     * 获取活跃的mp列表
     */
    public function getActiveList() {
        return $this->where(array('status' => 3))->select();
    }
    
    /**
     * 获得公众号列表
     */
    public function getPublicByMpid($mpids){
        $sql = "select wea.*,m.nickname,m.header,o.name from {$this->tablePrefix}wx_ent_app as wea
                left join {$this->tablePrefix}member as m on wea.uid = m.uid
                left join {$this->tablePrefix}organization as o on wea.organiz_id = o.id
                where wea.status <> 4 and wea.mp_id in (".implode(',',$mpids).")";

        return $this->query($sql);
    }

    /**
     * 解除托管
     */
    public function remove($mp_id, $uid) {
        return $this->where(array('mp_id' => $mp_id, 'uid' => $uid))->setfield('status', 5);
    }
	
    /**
     * 更新信息
     * @param unknown $mpId
     * @param unknown $data
     */
	public function updateInfo($mpId, $data=array()){
		return $this->where(array('mp_id'=>$mpId))->save($data);
	}
	
	/**
	 * 获取微信对象
	 */
	public function getWxObj($mp_id) {
	    $info = $this->getInfoById($mp_id);
	    return getWxObj($info);
	    //初始化微信操作对象
	    /*$options = array (
	        'token'             => $info['data_fetcher_token'],  // 填写你设定的key
	        'appid'             => $info['app_id'],
	        'appsecret'         => $info['app_secret']
	    );
	
	    $weObj  = new Wechat($options);
	
	    return $weObj;
	    */
	}
}
